<?php

namespace wangbj\upload;

use think\Exception;
use think\facade\Config;

/**
 * 存储模块驱动
 * Class driver
 * @package app\common\library\storage
 */
class UploadManage
{
    private $config;    // upload 配置
    private $engine;    // 当前存储引擎类
    private $engineName;    // 当前存储引擎类名称

    /**
     * 构造方法
     * @throws Exception
     */
    public function __construct()
    {
        $this->config = Config::get('upload.');
    }

    public function storage($storage = null){
        if(empty($storage) || $storage == $this->engineName) {
            if ($this->engine) return $this->engine;
        }
        $this->engine = $this->getEngineClass($storage);
        return $this;
    }


    /**
     * 设置上传的文件信息
     * @param $name
     * @return mixed
     */
    public function setUploadFile($name = 'iFile')
    {
        return $this->engine->setUploadFile($name);
    }

    /**
     * 设置上传的文件信息
     * @param $filePath
     * @return mixed
     */
    public function setUploadFileByReal($filePath)
    {
        return $this->engine->setUploadFileByReal($filePath);
    }

    /**
     * 执行文件上传
     * @param $save_dir
     * @return mixed
     */
    public function upload($save_dir)
    {
        return $this->engine->upload($save_dir);
    }

    /**
     * 抓取网络资源
     * @param $url
     * @param $key
     * @return mixed
     */
    public function fetch($url, $key) {
        return $this->engine->fetch($url, $key);
    }

    /**
     * 执行文件删除
     * @param $fileName
     * @return mixed
     */
    public function delete($fileName)
    {
        return $this->engine->delete($fileName);
    }

    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->engine->getError();
    }

    /**
     * 获取文件路径
     * @return mixed
     */
    public function getFileName()
    {
        return $this->engine->getFileName();
    }

    /**
     * 返回文件信息
     * @return mixed
     */
    public function getFileInfo()
    {
        return $this->engine->getFileInfo();
    }

    /**
     * 获取当前的存储引擎
     * @param $storage
     * @return mixed
     * @throws Exception
     */
    private function getEngineClass($storage = null)
    {
        $engineName = is_null($storage) ? $this->config['default'] : $storage;
        $this->engineName = $engineName;
        $classSpace = __NAMESPACE__ . '\\engine\\' . ucfirst($engineName);
        if (!class_exists($classSpace)) {
            throw new Exception('未找到存储引擎类: ' . $engineName);
        }
        if($engineName == 'local') {
            $engine = new $classSpace();
        } else {
            $engine = new $classSpace($this->config[$engineName]);
        }
        $engine->setUploadValidate($this->config['validate']);
        return $engine;
    }


    /**
     * 获取文件全路径
     * @param $uri
     * @param $type
     * @return mixed|string
     */
    public function getFileUrl($uri='',$type='')
    {
        if (strstr($uri, 'http://'))  return $uri;
        if (strstr($uri, 'https://')) return $uri;

        $engine = $this->engineName;
        if (empty($engine) || $engine === 'local') {
            //图片分享处理
            if ($type && $type == 'share') {
                return ROOT_PATH . $uri;
            }
            $domain = request()->domain(true);
        } else {
            $domain = $this->config[$engine]['domain'];
        }
        return $this->format($domain, $uri);
    }

    /**
     * 设置文件路径转相对路径
     * @param $uri
     * @return array|mixed|string|string[]
     */
    public function setFileUrl($uri='')
    {
        $engine = $this->engineName;
        if (empty($engine) || $engine === 'local') {
            $domain = request()->domain();
            return str_replace($domain.'/', '', $uri);
        } else {
            $domain = $this->config[$engine]['domain'];
            return str_replace($domain, '', $uri);
        }
    }


    /**
     * 处理域名
     * @param $domain
     * @param $uri
     * @return string
     */
    public function format($domain, $uri)
    {
        // 处理域名
        $domainLen = strlen($domain);
        $domainRight = substr($domain, $domainLen -1, 1);
        if ('/' == $domainRight) {
            $domain = substr_replace($domain,'',$domainLen -1, 1);
        }

        // 处理uri
        $uriLeft = substr($uri, 0, 1);
        if('/' == $uriLeft) {
            $uri = substr_replace($uri,'',0, 1);
        }

        return trim($domain) . '/' . trim($uri);
    }

}
